package org.anachronos.jeep.agent;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import org.anachronos.jeep.core.trace.TraceModelBuilder;
import org.anachronos.jeep.core.trace.impl.Trace;

public class ShutdownHook extends Thread {
	private final static Logger logger = Logger.getLogger(ShutdownHook.class.getName());
	
	private final String destDir;

	public ShutdownHook(String destDir) {
		super();
		this.destDir = destDir == null ? "profiler/" : destDir;
		
		createDir();
	}

	private void createDir() {
		File dir = new File(this.destDir);
		if (!dir.exists()) {
			boolean mkdirs = dir.mkdirs();
			if (!mkdirs) {
				logger.warning("Could not create destDir:" + destDir + "!");				
			}
		}
	}
	
	@Override
	public void run() {
		super.run();
		Trace trace = TraceModelBuilder.stopProfiling();
		DecimalFormat decimalFormat = new DecimalFormat();
		decimalFormat.setGroupingUsed(true);
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
			Date date = new Date();
			File traceFile = new File(destDir, format.format(date) + ".trace");
			String fileName = traceFile.getAbsolutePath();
			TraceModelBuilder.save(trace, fileName);
		} catch (Exception e) {
			logger.throwing(getClass().getName(), "run", e);
			throw new RuntimeException(e);
		}
	}
}
